<?php
namespace app\home\controller;

use app\admin\controller\Ajax;
use app\home\logic\CartLogic;
use app\home\logic\OrderLogic;
use think\AjaxPage2;

class Order extends Base {

    public $user;
    public $shop_order_status;

    public function _initialize(){
        parent::_initialize();
        $this->shop_order_status = C('shop_order_status');
        $this->assign('shop_order_status',$this->shop_order_status);
        $this->user = $this->user();
    }

    //会员充值
    public function recharge(){
        if (!$this->user) $this->redirect('User/login');
        if (IS_AJAX){
            $amount = I('param.amount');
            //if (!num($amount)) ajaxReturn(array('status' => 500,'msg' => '充值金额数据有误'));
            if ($amount <= 0) ajaxReturn(array('status' => 500,'msg' => '充值金额数据有误'));
            $order['user_id'] = $this->user['user_id'];
            $order['amount'] = $amount;
            $order['add_time'] = time();
            $recharge_id = M('recharge')->insertGetId($order);
            ajaxReturn(array('status' => 200,'msg' => '正在前往支付...','result' => $recharge_id));
        }
        $this->assign('title','会员充值');
        return $this->fetch();
    }

    //消费记录
    public function expense(){
        if (!$this->user) $this->redirect('User/login');
        $expense = M('expense')->where(array('user_id' => $this->user['user_id']))->order('add_time desc')->select();
        $this->assign('balance',$this->user['balance']);
        $this->assign('list',$expense);
        $this->assign('title','消费记录');
        return $this->fetch();
    }


    //预下单
    public function place_order(){
        if (!$this->user) $this->redirect('User/login');
        if (IS_AJAX){ //先将所有值，写入session
            if (!$this->user) ajaxReturn(array('status' => 404));
            $data = trim_array_element(I('param.'));
            $data['yd_date'] != '' ? session('yd_date',$data['yd_date']) : false; //预订的日期
            $data['yd_week'] != '' ? session('yd_week',$data['yd_week']) : false; //周数
            $data['yd_time'] != '' ? session('yd_time',$data['yd_time']) : false; //预订的时间
            $data['goods_id'] != '' ? session('goods_id',$data['goods_id']) : false; //预订的球位
            $data['coach_id'] != '' ? session('coach_id',$data['coach_id']) : false; //教练id
            $data['duoxuan'] != '' ? session('duoxuan',$data['duoxuan']) : false; //多选
            ajaxReturn(array('status' => 200));
        }
        //商品基本信息
        $goods = M('goods')->where(array('goods_id' => session('goods_id')))->find();
        $goods['vip_price'] = (float) $goods['vip_price'];
        $duoxuan = session('duoxuan');
        $dox = array_filter(explode(',',$duoxuan));
        if ($duoxuan != '' && count($dox) > 1){
            $amount = 0; //价格总计
            $original_price = 0 ;//原价总计
            $duoxuan = explode(',',$duoxuan);
            foreach ($duoxuan as $key=>$val){
                $result = explode('-',$val);
                $amount += $result[1];
                $original_price += is_numeric($result[2]) ? $result[2] : $result[1];
            }

            $this->assign('duoxuan_count',count($duoxuan)-1);

            $goods['amount'] = $amount;
            $this->assign('duoxuan',session('duoxuan'));
            session('duoxuan',null); //教练id
            $this->assign('original_price',$original_price);
        }else{
            //获取价格
            $array = array();
            $amount = array();
            if ((date('w',strtotime(session('yd_date'))) == 6) || (date('w',strtotime(session('yd_date'))) == 0)){ //是周末
                $amount = array('am' => $goods['weekend_price_am'],'pm' => $goods['weekend_price_pm'],'en' => $goods['weekend_price_en']);
            }else{ //不是周末
                $amount = array('am' => $goods['weekdays_price_am'],'pm' => $goods['weekdays_price_pm'],'en' => $goods['weekdays_price_en']);
            }
            //是否有设置节假日价格
            if ($goods['season_price'] != ''){
                //获取设置的每个单日价格
                $prices = explode(',',$goods['season_price']);
                foreach ($prices as $key=>$val){
                    $array[] = explode('|',$val);
                }
                if (!empty($array)){
                    foreach ($array as $k=>$v){
                        if (strtotime(session('yd_date')) == strtotime($v[0])){ //预订时间在节假日内
                            $amount = array('am' => $v[1],'pm' => $v[2],'en' => $v[3]);
                        }else{
                            continue;
                        }
                    }
                }
            }

            if (strtotime(session('yd_time')) < strtotime('12:00')){ //上午时间段
                $goods['amount'] = $amount['am'];
            }

            if ((strtotime(session('yd_time')) < strtotime('18:00')) && (strtotime(session('yd_time')) >= strtotime('12:00'))){//下午
                $goods['amount'] = $amount['pm'];
            }

            if ((strtotime(session('yd_time')) < strtotime('22:00')) && (strtotime(session('yd_time')) >= strtotime('18:00'))){//晚上
                $goods['amount'] = $amount['en'];
            }
            $this->assign('duoxuan_count',1);
        }

        //dump(session('coach_id'));
        //获取教练信息
        $coach = M('coachs')->where(array('coach_id' => session('coach_id')))->find();


        //手机号码
        $this->assign('phone',$this->user['phone']);
        //姓名
        $last_order = M('order')->where(array('user_id' => $this->user['user_id']))->order('add_time desc')->limit(1)->select();
        $this->assign('username',$last_order[0]['username']);
		//清空教练id
		session('coach_id',null); //教练id

            $coupon = M('coupon')
            ->where([
                'user_id'=>$this->user['user_id'],
                'use'=>0,
                'delete_time'=>0
            ])
            ->where('expiration_time','> time',date('Y-m-d'))
            ->field([
               'coupon_id',
               'title',
               'amount',
            ])
            ->select();
        $this->assign('coupon',$coupon);
		//dump(session('coach_id'));die;
        $this->assign('goods',$goods);
       // pr($goods);
        $this->assign('coach',$coach);
        $this->assign('yd_date',session('yd_date'));
        $this->assign('yd_week',session('yd_week'));
        $this->assign('yd_time',session('yd_time'));
        $this->assign('user',$this->user);
        $this->assign('order_sn',date('mdHis',time()).rand(10000,99999));
        $this->assign('title','预订球位-预下单');

        return $this->fetch();
    }


    public function add_order(){
        if (IS_AJAX){
            if (!$this->user) ajaxReturn(array('status' => 404,'msg' => '登录信息缺失，请先前往登录','url' => U('User/login')));
            $data = trim_array_element(I('param.'));
            $coupon = M('coupon')->where([
                'coupon_id'=>explode('-',$data['coupon_id'])[0],
                'user_id'=>$this->user['user_id'],
                'use'=>0,
                'delete_time'=>0,
            ])
             ->where('expiration_time','> time',date('Y-m-d'))
             ->field([
                 'coupon_id',
                 'amount'
             ])
              ->find();
            if ( $data['coupon_id'] && empty($coupon) )  ajaxReturn(array('status' => 500,'msg' => '您没有此优惠卷哦'));
            if ($data['duoxuan'] != ''){ //多选订单
                $duoxuan = explode(',',$data['duoxuan']);
                foreach ($duoxuan as $key=>$val){
                    if ($val != ''){ //有值
                        $result = explode('-',$val);
                        if (time() >= strtotime($data['date'].' '.$result[0]) && $key == 0) {
                            ajaxReturn(array('status' => 500,'msg' => $data['date'].' '.$result[0].'已过期'));
                        }
                        $time = $data['date']." ".$result[0];
                        $count = M('order')->where(array('subscribe_time' => strtotime($time),'goods_id' => $data['goods_id'],'order_status' => ['in',[0,1]]))->count();
                        if ($count > 0) {
                            ajaxReturn(array('status' => 500,'msg' => $data['date']." ".$result[0].'已被预定'));
                        }
                    }
                }
                if(empty($data['username']) || empty($data['phone'])){
                    ajaxReturn(array('status' => 500,'msg' => '姓名、电话'));
                }
                if (!check_mobile($data['phone'])) ajaxReturn(array('status' => 500,'msg' => '手机号码格式不正确'));

                foreach ($duoxuan as $k=>$v){
                    if ($v != ''){ //有值
                        $result = explode('-',$v);
                        $time = $data['date']." ".$result[0];
                        //添加订单
                        $map['order_sn'] = $data['order_sn']; //订单编号
                        $map['user_id'] = $this->user['user_id']; //用户
                        if ($k == 0){
                            $map['goods_price'] = $data['amount']; //金额
                            $data['coach_id'] != '' ? $map['coach_id'] = $data['coach_id'] : false;
                            $map['user_note'] = $data['user_note']; //用户备注
                        }else{
                            $map['goods_price'] = $result[1];
                            $map['user_note'] = $data['order_sn'].'子订单';
                        }
                        $map['add_time'] = time(); //下单日期
                        $map['username'] = $data['username']; //预订人
                        $map['phone'] = $data['phone']; //联系电话
                        $map['subscribe_time'] = strtotime($time); //预约时间
                        $map['week'] = $data['week']; //周数
                        $map['goods_id'] = $data['goods_id']; //球位商品id
                        $map['goods_name'] = M('goods')->where(array('goods_id' => $data['goods_id']))->getField('goods_name'); //球位名称
                        $map['coupon_id'] =  explode('-',$data['coupon_id'])[0];
                        M('order')->insert($map);
                    }
                }
            }else{
                if (time() >= strtotime($data['date'].' '.$data['time'])) ajaxReturn(array('status' => 500,'msg' => '预约时间已过期'));
                if(empty($data['username']) || empty($data['phone'])){
                    ajaxReturn(array('status' => 500,'msg' => '姓名、电话'));
                }
                if (!check_mobile($data['phone'])) ajaxReturn(array('status' => 500,'msg' => '手机号码格式不正确'));
                //这个时间段是否已经有人预定了 不包括已经取消的订单
                $time = $data['date']." ".$data['time'];
                $count = M('order')->where(array('subscribe_time' => strtotime($time),'goods_id' => $data['goods_id'],'order_status' => ['in',[0,1]]))->count();
                if ($count > 0) {
                    ajaxReturn(array('status' => 500,'msg' => '该时段已被预定'));
                }
                //添加订单
                $map['order_sn'] = $data['order_sn']; //订单编号
                $map['user_id'] = $this->user['user_id']; //用户
                $map['goods_price'] = $data['amount']; //金额
                $map['add_time'] = time(); //下单日期
                $map['username'] = $data['username']; //预订人
                $map['phone'] = $data['phone']; //联系电话
                $map['user_note'] = $data['user_note']; //用户备注
                $map['subscribe_time'] = strtotime($time); //预约时间
                $map['week'] = $data['week']; //周数
                $map['goods_id'] = $data['goods_id']; //球位商品id
                $map['goods_name'] = M('goods')->where(array('goods_id' => $data['goods_id']))->getField('goods_name'); //球位名称
                $data['coach_id'] != '' ? $map['coach_id'] = $data['coach_id'] : false;
                $map['coupon_id'] =  explode('-',$data['coupon_id'])[0];
                $id = M('order')->insertGetId($map);
            }
            //清空session
            session('yd_date',null); //教练id
            session('yd_week',null); //教练id
            session('yd_time',null); //教练id
            session('goods_id',null); //教练id
            ajaxReturn(array('status' => 200,'msg' => '下单成功，请前往支付...','url' => U('Payment/pay_order',array('itemid' => $data['order_sn']))));
        }
    }


    //订单列表
    public function index(){
        if (!$this->user) $this->redirect('User/login');
        $this->assign('title','我的订单');
        return $this->fetch();
    }

    public function ajax_index(){
        $order_status = I('param.id');
        $where['user_id'] = $this->user['user_id'];
        $where['deleted'] = 0;
        if ($order_status != 3){
            $where['order_status'] = $order_status;
        }
        $list = M('order')->where($where)->order('add_time desc')->select();

        foreach ($list as $key=>$val){
        	$time = date('H:i',$val['subscribe_time']);
        	if ($time == '9:00') $list[$key]['end_time'] = '10:00';
        	if ($time == '10:05') $list[$key]['end_time'] = '11:05';
        	if ($time == '11:10') $list[$key]['end_time'] = '12:10';
        	if ($time == '12:15') $list[$key]['end_time'] = '13:15';
        	if ($time == '13:20') $list[$key]['end_time'] = '14:20';
        	if ($time == '14:25') $list[$key]['end_time'] = '15:25';
        	if ($time == '15:30') $list[$key]['end_time'] = '16:30';
        	if ($time == '16:35') $list[$key]['end_time'] = '17:35';
        	if ($time == '17:40') $list[$key]['end_time'] = '18:40';
        	if ($time == '18:45') $list[$key]['end_time'] = '19:45';
        	if ($time == '19:50') $list[$key]['end_time'] = '20:50';
        	if ($time == '20:55') $list[$key]['end_time'] = '21:55';
        }
        $this->assign('list',$list);
        return $this->fetch();
    }

    //删除订单
    public function del_order(){
        if (!$this->user) $this->redirect('User/login');
        $order_id = I('param.id');
        $order = M('order')->where(array('order_id' => $order_id))->find();
        if ($order['order_status'] == 1) ajaxReturn(array('status' => 500,'msg' => '订单状态不符合，不可删除'));
        M('order')->where(array('order_id' => $order_id))->save(array('deleted' => 1));
        ajaxReturn(array('status' => 200,'msg' => '删除成功','url' => U('Order/index')));
    }

    //商场订单列表
    public function shop_index(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        $count['status_1'] = M('shop_order')->where(array('order_status' => 0,'user_id' => $this->user['user_id']))->count();
        $count['status_2'] = M('shop_order')->where(array('order_status' => 1,'user_id' => $this->user['user_id']))->count();
        $count['status_3'] = M('shop_order')->where(array('order_status' => 2,'user_id' => $this->user['user_id']))->count();
        $this->assign('count',$count);
        $this->assign('title','我的订单');
        return $this->fetch();
    }

    public function ajax_shop_index(){
        $order_status = I('param.id');
        $where['user_id'] = $this->user['user_id'];
        $where['deleted'] = 0;
        if ($order_status != ''){
            $where['order_status'] = $order_status;
        }
        $list = M('shop_order')->where($where)->order('add_time desc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['order_goods'] = M('order_goods')->where(array('order_id' => $val['order_id']))->select();
            foreach ($list[$key]['order_goods'] as $m=>$n){
                $list[$key]['order_goods'][$m]['original_img'] = M('goods')->where(array('goods_id' => $n['goods_id']))->getField('original_img');
            }
        }
        $this->assign('list',$list);
       // pr($list,1);
        return $this->fetch();
    }


    //商场订单详情
    public function shop_detail(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        $item_id = I('param.item_id');
        $order = M('shop_order')->where(array('order_id' => $item_id))->find();
        $order_goods = M('order_goods')->where(array('order_id' => $order['order_id']))->select();
        foreach ($order_goods as $key=>$val){
            $order_goods[$key]['original_img'] = M('goods')->where(array('goods_id' => $val['goods_id']))->getField('original_img');
        }
        $this->assign('order',$order);
        $this->assign('order_goods',$order_goods);
        $this->assign('title','订单详情');
        return $this->fetch();
    }

    //确认收货
    public function confirm_receipt(){
        if (!$this->user) ajaxReturn(array('status' => 401,'url' => U('User/login',array('type' => 2))));
        $item_id = I('param.item_id');
        $order = M('shop_order')->where(array('order_id' => $item_id))->find();
        if ($order['order_status'] != 2) ajaxReturn(array('status' => 500,'msg' => '500:订单状态错误'));
        M('shop_order')->where(array('order_id' => $item_id))->save(array('order_status' => 3,'turnover_time' => time()));
        ajaxReturn(array('status' => 200,'msg' => '确认成功','url' => U('Order/shop_detail',array('item_id' => $order['order_id']))));
    }

    //删除订单
    public function del_shop_order(){
        if (!$this->user) ajaxReturn(array('status' => 401,'url' => U('User/login',array('type' => 2))));
        $item_id = I('param.item_id');
        $order = M('shop_order')->where(array('order_id' => $item_id))->find();
        if (!$order) ajaxReturn(array('status' => 500,'msg' => '500:订单参数错误'));
        M('shop_order')->where(array('order_id' => $item_id))->save(array('deleted' => 1));
        ajaxReturn(array('status' => 200,'msg' => '删除成功','url' => U('Order/shop_index')));
    }

    //订餐订单
    public function meal_order(){
        if (!$this->user) $this->redirect('User/login',array('type' => 3));
        $this->assign('title','我的订单');
        $list = M('meal_order')->where(array('user_id' => $this->user['user_id']))->order('add_time desc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['order_goods'] = M('meal_order_goods')->where(array('order_id' => $val['order_id']))->select();
            foreach ($list[$key]['order_goods'] as $m=>$n){
                $list[$key]['order_goods'][$m]['original_img'] = M('goods')->where(array('goods_id' => $n['goods_id']))->getField('original_img');
            }
        }
        $this->assign('list',$list);
        return $this->fetch();
    }

    //再来一单
    public function again(){
        if (!$this->user) ajaxReturn(array('status' => 401,'url' => U('User/login',array('type' => 3))));
        $item_id = I('param.item_id');
        $order_goods = M('meal_order_goods')->where(array('order_id' => $item_id))->select();
        foreach ($order_goods as $key=>$val){
            $catch['user_id']            = $this->user['user_id'];
            $catch['cat_id']             = M('goods')->where(array('goods_id' => $val['goods_id']))->getField('cat_id');
            $catch['goods_id']           = $val['goods_id']; // 商品id
            $catch['goods_name']         = $val['goods_name']; // 商品名称
            $catch['goods_sn']           = $val['goods_sn']; // 商品货号
            $catch['goods_num']          = $val['goods_num']; // 购买数量
            $catch['goods_price']        = $val['goods_price']; // 商品价
            $catch['spec_key']           = $val['spec_key']; // 商品规格
            $catch['spec_key_name']      = $val['spec_key_name']; // 商品规格名称
            $catch['selected']           = 1; //选中
            $catch['add_time']           = time(); //加入时间
            M('meal_cart')->insert($catch);
        }
        ajaxReturn(array('status' => 200,'msg' => '成功','url' => U('Goods/order_index',array('is_show' => 1))));
    }

	//删除点餐订单
	public function del_meal_order(){
		if (!$this->user) ajaxReturn(array('status' => 401,'url' => U('User/login',array('type' => 3))));
		$item_id = I('param.item_id');
		$order =  M('meal_order')->where(array('order_id' => $item_id))->find();
		if ($order['order_status'] != -1 && $order['order_status'] != 2) ajaxReturn(array('status' => 500,'msg' => '订单状态不符合'));
		M('meal_order')->where(array('order_id' => $item_id))->delete();
		ajaxReturn(array('status' => 200,'msg' => '删除成功','url' => U('Order/meal_order')));
	}


    /***
     * 订单评价
     * @return mixed
     */
	public function evaluate(){
        return $this->fetch();
    }


    /*
     * 修改订单评价
     */
    public function operate(){
	        $post = $this->request->post();

            $data = M('shop_order')
                ->where(array('order_id' => $post['order_id']))
                ->update([
                    'content' => $post['content'],
                    'level'=>$post['level'],
                    'evaluation_time'=>time()
                ]);
            $data ?
                ajaxReturn(array('status' => 200,'msg' => '评论成功','url' => U('Order/shop_detail',['item_id'=>$post['id']])))
                :
                ajaxReturn(array('status' => 500,'msg' => '500:订单参数错误'));
    }






}